package se_report

import (
	"fmt"
	"strconv"
	"strings"
	"time"
	"wx-api/adx-api/cache"
	"wx-api/adx-api/config"
	"wx-api/adx-api/errmsg"
	"wx-api/adx-api/handlers"
	"wx-api/adx-api/services/comm"
	"wx-api/adx-api/utils"
)

func AdxChannelReport(c *handlers.Controller) {
	var form ParamReport
	if err := c.Ctx.ShouldBind(&form); err != nil {
		fmt.Println(err)
		c.BadRequest()
		return
	}
	adx_uid := comm.GetUserInfo(c)
	if adx_uid == "" {
		return
	}
	if form.Page == 0 {
		form.Page = 1
	}
	if form.PageSize == 0 {
		form.PageSize = 50
	}
	if form.Sdate == "" {
		form.Sdate = time.Now().Format("2006-01-02")
	}
	if form.Edata == "" {
		form.Edata = time.Now().Format("2006-01-02")
	}
	if len(form.Group) == 0 {
		form.Group = []string{"date"}
	}
	if !utils.CkArrs(form.Group, "date") {
		form.Group = append(form.Group, "date")
	}
	form.Group = utils.UnqArrs(form.Group)
	sql := "select "
	//date,adx_id,media_id,slot_id,
	sumsql := " ,sum(dsp_req) as req,sum(dsp_fill) as fill, " +
		"sum(pv) as pv, sum(ipv) as ipv, sum(click) as click, sum(iclick) as iclick, " +
		"sum(deeplink) as deeplink,sum(ideeplink) as ideeplink,sum(adx_price) as adx_price,sum(dsp_price) as dsp_price " +
		"from " + config.CkTableReport
	where := " where dsp_id !='' "
	group_str := strings.Join(form.Group, ",")
	if form.Sdate == form.Edata {
		where += " and date ='" + form.Sdate + "'"
	}
	if form.Sdate != form.Edata {
		where += " and date >='" + form.Edata + "' and date <= '" + form.Sdate + "'"
	}
	if len(form.DspIds) > 0 {
		where += " and dsp_id in ('" + strings.Join(form.DspIds, "','") + "')"
	}
	if len(form.PosIds) > 0 {
		where += " and pos_id in ('" + strings.Join(form.PosIds, "','") + "')"
	}
	order := " order by date desc"
	group := " group by " + group_str
	if utils.CkArrs(form.Group, "date_hour") {
		order = " order by date,date_hour desc"
	}
	limitto := (form.Page - 1) * form.PageSize
	limitfo := form.PageSize
	limit := " limit " + strconv.Itoa(int(limitto)) + "," + strconv.Itoa(int(limitfo))
	//获取总页数
	count := config.GetCkCount(config.CkTableReport + where + group)
	retd := config.DataList{
		PageSize: form.PageSize,
		PageNum:  form.Page,
		Total:    count,
	}

	sql = sql + group_str + sumsql + where + group + order + limit
	ret := []AdxChannelCkReport{}
	err := config.CKDB.Select(&ret, sql)
	if err != nil {
		fmt.Println("select error:" + err.Error())
		return
	}
	for i, val := range ret {
		if val.Fill == 0 && val.Pv == 0 && val.Ipv == 0 {
			continue
		}
		ainfo, ok := cache.CacheChannelListMapNGet(val.DspId)
		if ok {
			val.DspName = ainfo.Name
		} else {
			val.DspName = "-"
		}
		slotinfo, ok := cache.CacheChannelSlotMapNGet(val.PosId)
		if ok {
			val.PosName = slotinfo.Name
		} else {
			val.PosName = "-"
		}
		val.Date = val.Date[0:10]
		val.AdxPrice = utils.Decimal(val.AdxPrice / 100000)
		val.DspPrice = utils.Decimal(val.DspPrice / 100000)
		rate := float64(0)
		if ok {
			n := 100 - ainfo.Rate
			if n < 0 {
				n = 0
			}
			rate = float64(n) / 100
		}
		val.Income = utils.Decimal(val.DspPrice * rate)
		val.Profit = utils.Decimal(val.Income - val.AdxPrice)
		val.ProfitRate = utils.RateF(val.Profit, val.DspPrice)
		val.FillRate = utils.Rate(val.Fill, val.Req)
		val.PvRate = utils.Rate(val.Pv, val.Fill)
		val.ClickRate = utils.Rate(val.Click, val.Pv)
		val.DeeplinkRate = utils.Rate(val.Deeplink, val.Click)
		ret[i] = val
	}
	retd.List = ret
	c.SetErrorMsg(retd, errmsg.SuccessMsg())
	return
}

type AdxChannelCkReport struct {
	Date         string  `db:"date" json:"date" bson:"date"`
	DateHour     string  `db:"date_hour" json:"date_hour" bson:"date_hour"`
	AdxId        string  `db:"adx_id" json:"adx_id" bson:"adx_id"`
	AdxName      string  `db:"_" json:"adx_name" bson:"adx_name"`
	MediaId      string  `db:"media_id" json:"media_id" bson:"media_id"`
	MediaName    string  `db:"_" json:"media_name" bson:"media_name"`
	SlotId       string  `db:"slot_id" json:"slot_id" bson:"slot_id"`
	SlotName     string  `db:"_" json:"slot_name" bson:"slot_name"`
	DspId        string  `db:"dsp_id" json:"dsp_id" bson:"dsp_id"`
	DspName      string  `db:"_" json:"dsp_name" bson:"dsp_name"`
	PosId        string  `db:"pos_id" json:"pos_id" bson:"pos_id"`
	PosName      string  `db:"_" json:"pos_name" bson:"pos_name"`
	Req          int64   `db:"req" json:"req" bson:"req"`
	Fill         int64   `db:"fill" json:"fill" bson:"fill"`
	Pv           int64   `db:"pv" json:"pv" bson:"pv"`
	Ipv          int64   `db:"ipv" json:"ipv" bson:"ipv"`
	Click        int64   `db:"click" json:"click" bson:"click"`
	Iclick       int64   `db:"iclick" json:"iclick" bson:"iclick"`
	Deeplink     int64   `db:"deeplink" json:"deeplink" bson:"deeplink"`
	Ideeplink    int64   `db:"ideeplink" json:"ideeplink" bson:"ideeplink"`
	AdxPrice     float64 `db:"adx_price" json:"adx_price" bson:"adx_price"`
	DspPrice     float64 `db:"dsp_price" json:"dsp_price" bson:"dsp_price"`
	Income       float64 `db:"_" json:"income" bson:"income"`           //真实消费金额=消费金额*（100%-分成比例）
	Profit       float64 `db:"_" json:"profit" bson:"profit"`           //利润=真实消费金额-成本
	ProfitRate   float64 `db:"_" json:"profit_rate" bson:"profit_rate"` //利润率=利润/消费金额
	FillRate     float64 `db:"_" json:"fill_rate" bson:"fill_rate"`
	PvRate       float64 `db:"_" json:"pv_rate" bson:"pv_rate"`
	ClickRate    float64 `db:"_" json:"click_rate" bson:"click_rate"`
	DeeplinkRate float64 `db:"_" json:"deeplink_rate" bson:"deeplink_rate"`
}
